/*
 * RtpRecvState.cpp
 *
 *  Created on: 2012-3-30
 *      Author: terry
 */

#include "RtpRecvState.h"
//#include "stdafx.h"
#include <limits>


RtpRecvState::RtpRecvState():
        m_clock(90000),
        m_startTime(),
        m_extTime(),
        m_ts(),
        m_packetCount()
{
}

RtpRecvState::~RtpRecvState()
{
}

void RtpRecvState::clear()
{
    m_clock = 90000;
    m_startTime = 0;
    m_extTime = 0;
    m_ts = 0;
    m_packetCount = 0;
}

uint64_t RtpRecvState::getCurRealTime()
{
    return (m_extTime + m_ts) / (m_clock / 1000);
}

void RtpRecvState::update(uint32_t ts)
{
    if (m_packetCount == 0)
    {
        m_startTime = ts;
        m_extTime = 0;
    }
    else if ((ts < m_ts) && ((ts - m_ts) < std::numeric_limits<uint32_t>::max()/2))
    {
        m_extTime += 0x100000000;
    }

    m_ts = ts;
    m_packetCount ++;
}

uint32_t RtpRecvState::getCurTime() const
{
    return m_ts;
}

uint64_t RtpRecvState::getTimeOffset() const
{
    uint64_t now = m_extTime + m_ts;
    return now - (uint64_t)m_startTime;
}

uint64_t RtpRecvState::getRealTimeOffset() const
{
    return getTimeOffset() / (m_clock / 1000);
}

void RtpRecvState::setClock(uint32_t clk)
{
    if ((clk > 1000) && ((clk % 100) == 0))
    {
        m_clock = clk;
    }
}

uint32_t RtpRecvState::getClock() const
{
    return m_clock;
}
